require 'rake/clean'
require 'albacore'
require 'uuidtools'

PROJECT_PATH = Dir.pwd
BUILD_ARCHIVE_OUTPUT_PATH = PROJECT_PATH + '/build-archive'

BUILD_ARCHIVE_TEMP_PATH = File.join(Dir.tmpdir, UUIDTools::UUID.timestamp_create())

ENVIRONMENT = ENV['environment'] ? ENV['environment'] : ENV['computername']

task :default => ['deploy:all']

namespace :deploy do
  
	task :all => [:unzip_latest_archive, :migrate_environment_configs]

	desc 'Unzip latest archive'
	unzip :unzip_latest_archive do |unzip|
		unzip.unzip_path = BUILD_ARCHIVE_TEMP_PATH
		unzip.zip_file = get_latest_archive_file_path()
	end
	
	def get_latest_archive_file_path()
		Dir.glob(File.join(BUILD_ARCHIVE_OUTPUT_PATH, '*.*')).max { |a,b| File.ctime(a) <=> File.ctime(b) }
	end
	
	desc 'Migrate environment configs'
	task :migrate_environment_configs do		
		build_archive_temp_environment_configs_path = File.join(BUILD_ARCHIVE_TEMP_PATH, 'EnvironmentConfigs')
		
		FileUtils.cp_r("#{build_archive_temp_environment_configs_path}/#{ENVIRONMENT}/.", BUILD_ARCHIVE_TEMP_PATH)
		
		FileUtils.remove_dir(build_archive_temp_environment_configs_path, true)
	end
		
	desc 'Cleanup'
	task :cleanup do
		FileUtils.remove_dir(BUILD_ARCHIVE_TEMP_PATH, true)
	end
		
end
